package cc.dowell.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cc.dowell.config.ContextHolder;
import cc.dowell.enums.HttpCodeEnum;
import cc.dowell.pojo.Fruit;
import cc.dowell.service.FruitService;
import cc.dowell.utils.R;
import cc.dowell.vo.FruitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/fruit")
public class FruitController {

    @Autowired
    private FruitService fruitService;

    @GetMapping("/{pageNum}/{pageSize}")
    public R list(@PathVariable long pageNum, @PathVariable long pageSize,@RequestParam String fruitName){
        Page<Fruit> page = new Page<>(pageNum, pageSize);
        IPage<FruitVo> fruitVoPage = fruitService.selectFruitPage(page,fruitName);
        System.out.println(fruitVoPage);
        return R.success(fruitVoPage);
    }

    @PostMapping
    public R add(@RequestBody Fruit fruit){
        Long userId = ContextHolder.getUserId();
        fruit.setCreateUserId(userId);
        boolean b = fruitService.save(fruit);
        if(b){
            return R.success(HttpCodeEnum.SUCCESS);
        }else{
            return R.error(HttpCodeEnum.ADD_FAIL);
        }
    }

    @PutMapping
    public R update(@RequestBody Fruit fruit){
        Long userId = ContextHolder.getUserId();
        fruit.setCreateUserId(userId);
        boolean b = fruitService.updateById(fruit);
        if(b){
            return R.success(HttpCodeEnum.SUCCESS);
        }else{
            return R.error(HttpCodeEnum.UPDATE_FAIl);
        }
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable int id){
        boolean b = fruitService.removeById(id);
        if(b){
            return R.success(HttpCodeEnum.SUCCESS);
        }else{
            return R.error(HttpCodeEnum.DELETE_FAIl);
        }
    }



}